﻿ using PlayListSet.Comm;
using PlayListSet.Entity;
using PlayListSet.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PlayListSet
{

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window,System.ComponentModel.INotifyPropertyChanged
    {
        public List<ChannelInfo> ChannelInfos { set; get; }
        private Dictionary<string, ObservableCollection<PlayInfoBase>> DicList;
        public static int TimeCodeLength = 120;
        public static int TimeCodeSeconds
        {
            get
            {
                return TimeCodeLength * 60;
            } 
        }
        public static MainWindow mainWindow1;
        public static MainWindow MainWindowStatic { get => mainWindow1; }

        public MainWindow()
        {
            TimeCodeLength = VCLib.Util.ConfigHelp.ReadConfig<int>("timeCodeLength");
            mainWindow1 = this;
            Closed += MainWindow_Closed;
            ChannelInfos = ChannelInfo.GetChannelInfos();
            InitializeComponent();
            //初始化时间码长度
           

            DicList = new Dictionary<string, ObservableCollection<PlayInfoBase>>();
            foreach (var channelInfo in ChannelInfos)
            {
                DicList.Add(channelInfo.ChannelName, new ObservableCollection<PlayInfoBase>());
            }
            List<PlayInfo> list = PlayInfo.Read();
            foreach (var info in list)
            {
                if (DicList.ContainsKey(info.Channel))
                {
                    DicList[info.Channel].Add(info);
                    info.ChannelInfo=GetSize(info.Channel).GetValueOrDefault();
                }
            }
            List<PlayCmd> listCMD = PlayCmd.Read();
            foreach (var info in listCMD)
            {
                if (DicList.ContainsKey(info.Channel))
                {
                    info.EndTimeCode = info.StartTimeCode + 35;
                    DicList[info.Channel].Add(info);
                }
            }


            //DicList.Add("墙面1", new ObservableCollection<PlayInfo>() {
            //    new PlayInfo(){   Name="疗愈1",  StartTimeCode=1000,EndTimeCode=1200,Channel="墙面1"},
            //      new PlayInfo(){  Name="疗愈2",  StartTimeCode=100,EndTimeCode=800,Channel="墙面1"}
            //});
            //DicList.Add("墙面2", new ObservableCollection<PlayInfo>() {
            //    new PlayInfo(){     Name="疗愈3",  StartTimeCode=1000,EndTimeCode=1200, Channel = "墙面2"},
            //      new PlayInfo(){  Name="疗愈4",  StartTimeCode=100,EndTimeCode=800,Channel="墙面2"}
            //});
            foreach (var item in DicList.Values)
            {
                foreach (var i in item)
                {
                    var info = i as PlayInfo;
                    if (info != null)
                    {
                        var size = GetSize(i.Channel);
                        if (size != null)
                        {

                            info.ChannelInfo = size.Value;
                        }
                    }
                   
                }
            }

            timeListPanel.DicList = DicList;
            AppControl.Instance.PlayInfoMap = DicList;
            AppControl.Instance.ChannelInfos = ChannelInfos;
            AppControl.Instance.Init(this);
            modelSelect.DataContext = AppControl.Instance;
            _playCtr1.DataContext = AppControl.Instance.TimeCodePlayContorl;
            _playCtr2.DataContext = AppControl.Instance.TimeCodePlayContorl;
            _playCtr3.DataContext = AppControl.Instance.TimeCodePlayContorl;



            _palyState.SetBinding(TextBlock.TextProperty, new Binding("PlaybackStateStr") { Source = AppControl.Instance.TimeCodePlayContorl });
            _palyLog.SetBinding(TextBlock.TextProperty, new Binding("LogMsg") { Source = AppControl.Instance });
            vol.Value = AppControl.Instance.AppConfig.Vol;
            vol.ValueChanged += Vol_ValueChanged;
            Loaded += (sender, e) =>
              {
                  modelSelect_Unchecked(null, null);
              };
        }

       

        private void MainWindow_Closed(object sender, EventArgs e)
        {
            playInfoCmdSetWin?.Close();
            AppControl.Instance.Close();
        }

        private Size? GetSize(string channel)
        {
            foreach (var item in ChannelInfos)
            {
                if (item.ChannelName == channel)
                    return new Size(item.SizeWidth, item.SizeHeight);
            }
            return null;
        }
        #region  new
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OPenNew();
        }
        public void OPenNew(int channelInfoSelectIndex = -1)
        {
            if (channelInfoSelectIndex >=0) 
            {
                ChannelInfoSelectIndex = channelInfoSelectIndex;
            }
            NewStartTimeCode = AppControl.Instance.TimeCodePlayContorl.GetCurrentTime().TotalSeconds;
            selectChannelPopup.IsOpen = true;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            selectChannelPopup.IsOpen = false;
        }
        private double _NewStartTimeCode = 0;

        public event PropertyChangedEventHandler PropertyChanged;

        public double NewStartTimeCode
        {
            set
            {
                _NewStartTimeCode = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("NewStartTimeCode"));
            }
            get
            {
                return _NewStartTimeCode;
            }
        }
        public string NewItemName { set; get; } = "节目1";
        private int channelInfoSelectIndex = 0;
        public int ChannelInfoSelectIndex
        {
            set
            {
                channelInfoSelectIndex = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ChannelInfoSelectIndex"));
            }
            get
            {
                return channelInfoSelectIndex;
            }
        }
        public int ProgramType { get; set; } = 0;
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if(ChannelInfos.Count ==0 )
            {
                MessageBox.Show("请先配置通道");
                return;
            }
            var channelName = ChannelInfos[ChannelInfoSelectIndex];
            PlayInfoBase playInfoBase;
            if (ProgramType == 0)
            {
                playInfoBase = new PlayInfo()
                {
                    Name = NewItemName,
                    StartTimeCode = NewStartTimeCode,
                    EndTimeCode = NewStartTimeCode + 200,
                    Channel = channelName.ChannelName,
                    ChannelInfo= new Size(channelName.SizeWidth, channelName.SizeHeight)
                };
            }
            else
            {
                playInfoBase = new PlayCmd()
                {
                    Name = NewItemName,
                    StartTimeCode = NewStartTimeCode,
                    EndTimeCode = NewStartTimeCode + 17.5,
                    Channel = channelName.ChannelName
                };
            }
        


            DicList[channelName.ChannelName].Add(playInfoBase);
            selectChannelPopup.IsOpen = false;
        }
        #endregion

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            try
            {
                List<PlayInfo> list = new List<PlayInfo>();
                List<PlayCmd> PlayCmds = new List<PlayCmd>();

                foreach (var key in DicList.Keys)
                {
                    foreach (var listItem in DicList[key])
                    {
                        var type = listItem.GetType();
                        if(type == typeof(PlayInfo))
                        {
                            list.Add((PlayInfo)listItem);
                        }else if(type == typeof(PlayCmd))
                        {
                            PlayCmds.Add((PlayCmd)listItem);
                        }
                       
                    }
                }
                PlayInfo.Save(list);
                PlayCmd.Save(PlayCmds);
                MessageBox.Show("保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败："+ex.Message);
            }
          
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            string baseUrl = System.IO.Path.Combine(
                System.AppDomain.CurrentDomain.BaseDirectory,"data"
                );
            if(!System.IO.Directory.Exists(baseUrl))
            {
                System.IO.Directory.CreateDirectory(baseUrl);
            }
            foreach (var key in DicList.Keys)
            {
                using (System.IO.TextWriter writer =
                     new System.IO.StreamWriter(
                         new System.IO.FileStream(System.IO.Path.Combine(baseUrl, key + ".txt"), System.IO.FileMode.Create, System.IO.FileAccess.Write)))
                {
                    writer.WriteLine(PlayInfo.GetTabLine());
                    foreach (var listItem in DicList[key])
                    {
                        var type = listItem.GetType();
                        if (type == typeof(PlayInfo))
                        {
                            var w = ((PlayInfo)listItem);
                            writer.WriteLine(w.GetLine());
                        }
                    }
                }
            }
            List<UpdateSourceModel> list = new List<UpdateSourceModel>();

            foreach (var key in DicList.Keys)
            {
                var channelInfo = ChannelInfos.Where(i=>i.ChannelName== key).FirstOrDefault();  
                list.Add(new UpdateSourceModel { 
                     Channel = key,
                    ChannelInfo = channelInfo,
                      CurrentSize = 0,
                       IsData = true,
                         Name = key+"节目数据",
                          SourceUrl= System.IO.Path.Combine(baseUrl, key + ".txt"),
                           Size = 0,
                            State = "等待更新",
                             Msg="",
                             ID=new PlayInfo().ID
                });
                foreach (var listItem in DicList[key])
                {
                    var type = listItem.GetType();
                    if (type == typeof(PlayInfo))
                    {

                        var playInfo = ((PlayInfo)listItem);
                        if (playInfo.SourceType == 0 || playInfo.SourceType == 1 || playInfo.SourceType == 2)
                        {
                            list.Add(new UpdateSourceModel
                            {
                                Channel = key,
                                ChannelInfo = channelInfo,
                                CurrentSize = 0,
                                IsData = false,
                                Name = listItem.Name,
                                SourceUrl = playInfo.SourceUrl,
                                Size = 0,
                                State = "等待更新",
                                Msg = "",
                                ID = listItem.ID
                            });
                        }
                    }

                }
            }

            UpdateSourceWindos updateSourceWindos   = new UpdateSourceWindos(list);
            updateSourceWindos.ShowDialog();
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            timeListPanel.ClearDic();
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            if(AppControl.Instance.TimeCodePlayContorl.PlaybackState== NAudio.Wave.PlaybackState.Paused)
            {
                AppControl.Instance.TimeCodePlayContorl.Play();
            }
            else if (AppControl.Instance.TimeCodePlayContorl.PlaybackState == NAudio.Wave.PlaybackState.Playing)
            {
                AppControl.Instance.TimeCodePlayContorl.Pause();
            }
            else
            {
                AppControl.Instance.TimeCodePlayContorl.Play();
            }


        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            AppControl.Instance.TimeCodePlayContorl.Stop();
        }

        private void modelSelect_Checked(object sender, RoutedEventArgs e)
        {
            AppControl.Instance.TimeCodePlayContorl.Pause();
            Grid.SetRow(timeListPanel, 2);
            Grid.SetRowSpan(timeListPanel, 1);
            timeListPanel.SetContextMenu(true);
        }

        private void modelSelect_Unchecked(object sender, RoutedEventArgs e)
        {
            Grid.SetRow(timeListPanel, 1);
            Grid.SetRowSpan(timeListPanel, 2);
            timeListPanel.SetContextMenu(false );
        }

        private void Button_Click_8(object sender, RoutedEventArgs e)
        {
            AppConfigSet appConfigSet = new AppConfigSet();
            appConfigSet.ShowDialog();
        }

        internal void SetVol(int v)
        {
            this.Dispatcher.Invoke(() => { 
                vol.Value = v;
            });

        }
        private void Vol_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            AppControl.Instance.AppConfig.Vol = (int)vol.Value;
            Task.Run(() => {
                try
                {

                    AppConfig.Save(AppControl.Instance.AppConfig);
                }
                finally
                {

                }
            });
        }
        PlayInfoCmdSetWin playInfoCmdSetWin;
        private void Button_Click_9(object sender, RoutedEventArgs e)
        {
            if(playInfoCmdSetWin == null)
            {
                playInfoCmdSetWin = new PlayInfoCmdSetWin();
                playInfoCmdSetWin.Closed += PlayInfoCmdSetWin_Closed;
                playInfoCmdSetWin.Show();
            }
            else
            {
                playInfoCmdSetWin.Activate();
            }
       
        }

        private void PlayInfoCmdSetWin_Closed(object sender, EventArgs e)
        {
            playInfoCmdSetWin = null;
        }
    }
}
